//
//  CZEmoticonKeyboard.swift
//  53.表情键盘新工程
//
//  Created by gzxzmac on 16/3/31.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit

class CZEmoticonKeyboard: UIView {
    
    // MARK: - 属性
    /// 键盘对应的textView
    weak var textView: UITextView?
    
    private let ReuseIdentifier = "ReuseIdentifier:"
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 216)
        super.init(frame: newFrame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        backgroundColor = UIColor.brownColor()
        
        // 添加控件
        addSubview(collectionView)
        addSubview(toolBar)
        addSubview(pageControl)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        // 添加约束
        // VFL
        // H: 水平,|父控件左边 |父控件右边
        // V: 垂直,|父控件顶部 |父控件底部
        //
        // [vc]: 一个view
        // collectionView水平
        /// constraintsWithVisualFormat: VFL,创建出来的是约束的数组
        /// VLF: 是不能约束CenterX,CenterY
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[vc]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["vc" : collectionView]))
        
        // collectionViewtoolBar
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : toolBar]))
        
        // 垂直
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(37)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView, "tb": toolBar]))
        
        // pageControl
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 26))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = collectionView.frame.size
    }

    // MARK: - 懒加载
    /// collectionView
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        clv.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        clv.bounces = false
        clv.pagingEnabled = true
        clv.showsHorizontalScrollIndicator = false
        
        clv.dataSource = self
        clv.delegate = self
        
        // 注册cell
        clv.registerClass(CZEmoticonKeyboardPageCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        
        return clv
    }()
    
    /// toolBar
    private lazy var toolBar: CZEmoticonToolBar = {
        let bar = CZEmoticonToolBar(packages: CZEmoticonPackageManager.sharedManager.packages)
        
        bar.delegate = self
        
        return bar
    }()
    
    /// pageControl
    private lazy var pageControl: UIPageControl = {
        let control = UIPageControl()
        
        // 设置
//        control.numberOfPages = 5
//        control.currentPage = 3
        
        // 设置图片,使用KVC设置隐藏成员变量的值
        // 没有选中的
        control.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
//        control.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
//        
//        // 选中的
        control.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
//        control.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        
//        UIPageControl.printIvars()
//        UITableView.printIvars()
        
        return control
    }()
}

// MARK: - 扩展 CZEmoticonKeyboard
extension CZEmoticonKeyboard: CZEmoticonToolBarDelegate {
    func emoticonToolBar(tooBar: CZEmoticonToolBar, didSelectType type: CZEmoticonToolBarButtonType) {
//        print("toolBar选中了: \(type), \(type.rawValue)")
        // 切换collectionView对应的section
        
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
        
        // 设置pageControl
        setupPageControl(indexPath)
//        pageControl.numberOfPages = CZEmoticonPackageManager.sharedManager.packages[indexPath.section].pageEmoticons.count
//        pageControl.currentPage = indexPath.item
    }
}

// MARK: - 扩展 6.实现CZEmoticonKeyboardPageCellDelegate
extension CZEmoticonKeyboard: CZEmoticonKeyboardPageCellDelegate {
    // 7.实现方法
    func didSelectDeleteButton() {
//        print("keyboard知道删除按钮被点击了")
        textView?.deleteBackward()
    }
    
    /// 一个表情被点击了
    func emoticonKeyboardPageCell(cell: CZEmoticonKeyboardPageCell, didSelectEmoticon emoticon: CZEmoticonModel) {
//        print("我在keyboard里面知道了cell点击了表情: \(emoticon)")
//
        // 给textView来设置对应的内容
        textView?.insetEmoticon(emoticon)
        
        // 往最近这组里面添加
        CZEmoticonPackageManager.sharedManager.addFavorate(emoticon)
    }
    
//    /**
//    给textView来设置对应的内容
//    
//    - parameter emoticon: 点击的模型
//    */
//    func insetEmoticon(emoticon: CZEmoticonModel) {
//        guard let tv = textView else {
//            // 断言,条件不成立就挂了
//            assert(false, "你没有传入textView")
//            return
//        }
//        
//        // 添加emoji表情
//        if let emoji = emoticon.emoji {
//            // 将emoji添加到textView上面
//            tv.insertText(emoji)
//            return
//        }
//        
//        // 图片表情
//        if let fullPngPath = emoticon.fullPngPath {
//            // 图片->附件->属性文本
//            let atachment = CZTextAttachment()
//            atachment.image = UIImage(named: fullPngPath)
//            // 设置表情名称给附件
//            atachment.chs = emoticon.chs
//            
//            let wh = (tv.font?.lineHeight ?? 20) * 0.8
//            // bounds和frame正好相反,往下移是负数
//            atachment.bounds = CGRect(x: 0, y: -3, width: wh, height: wh)
//            
//            // 转成可变的属性文本
//            let attrM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: atachment))
//            
//            // 给附件设置UIFont属性,不然后面的表情会很小
//            attrM.addAttribute(NSFontAttributeName, value: tv.font!, range: NSRange(location: 0, length: 1))
//            
//            // 不能直接替换属性文本.拿到之前的属性文本
//            let oldAtrrM = NSMutableAttributedString(attributedString: tv.attributedText)
//            
//            let oldRange = tv.selectedRange
//            // 将附件添加到之前的属性文本里面
//            oldAtrrM.replaceCharactersInRange(oldRange, withAttributedString: attrM)
//            
//            tv.attributedText = oldAtrrM
//            
//            // 光标会跑到最后去
//            tv.selectedRange = NSRange(location: oldRange.location + 1, length: 0)
//        }
//    }
}

// MARK: - 扩展 CZEmoticonKeyboard
extension CZEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    // 返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonPackageManager.sharedManager.packages.count
    }
    
    // 每组返回多少个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonPackageManager.sharedManager.packages[section].pageEmoticons.count
    }
    
    // 返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! CZEmoticonKeyboardPageCell
        
//        cell.backgroundColor = UIColor.random()
        cell.indexPath = indexPath
        
        // 设置模型
        cell.emoticons = CZEmoticonPackageManager.sharedManager.packages[indexPath.section].pageEmoticons[indexPath.item]
        
        // 5.设置代理
        cell.delegate = self
        
        return cell
    }
    
    // 监听colletionView滚动,来动态设置toolBar上的按钮选中
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 计算中心参照点
        var refPoint = scrollView.center
        refPoint.x += scrollView.contentOffset.x
//        print("center: \(refPoint)")
        
        // 判断哪个cell包含这个参照点
        for cell in collectionView.visibleCells() {
            if cell.frame.contains(refPoint) {
                // 显示这个cell所在的组
                let indexPath = collectionView.indexPathForCell(cell)
//                print("选中: \(indexPath?.section) 组")
                
                // 让toolBar选中按钮
                toolBar.switchSelectedButtonWithSection(indexPath!.section)
                
                // 设置pageControl
                setupPageControl(indexPath!)
                break
            }
        }
    }
    
    /**
     设置PageControl
     
     - parameter indexPath: indexPath
     */
    private func setupPageControl(indexPath: NSIndexPath) {
        // 设置pageControl
        pageControl.numberOfPages = CZEmoticonPackageManager.sharedManager.packages[indexPath.section].pageEmoticons.count
        pageControl.currentPage = indexPath.item
        
        // 判断是否需要隐藏pageControl
        pageControl.hidden = indexPath.section == 0
    }
}
